package com.gosophia.conferenceManagement.scheme.ws.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.gosophia.commons.DozerChangeUtil;
import com.gosophia.commons.OrderCondition;
import com.gosophia.commons.Page;
import com.gosophia.commons.PropertyFilter;
import com.gosophia.commons.exception.BusinessException;
import com.gosophia.commons.exception.ConcurrencyException;
import com.gosophia.commons.exception.ParameterException;
import com.gosophia.commons.exception.TechnicalException;
import com.gosophia.conferenceManagement.common.dto.DocumentDTO;
import com.gosophia.conferenceManagement.common.entity.Document;
import com.gosophia.conferenceManagement.common.ws.impl.ConferenceHandleWebServiceImpl;
import com.gosophia.conferenceManagement.scheme.dto.SchemeJobDataDTO;
import com.gosophia.conferenceManagement.scheme.dto.SchemeTransientStoreDTO;
import com.gosophia.conferenceManagement.scheme.entity.SchemeJobData;
import com.gosophia.conferenceManagement.scheme.entity.SchemeTransientStore;
import com.gosophia.conferenceManagement.scheme.service.ConferenceSchemeService;
import com.gosophia.conferenceManagement.scheme.ws.ConferenceSchemeWebService;
import com.gosophia.dataDictionary.dto.DataValueDTO;
import com.gosophia.dataDictionary.entity.DataValue;
import com.gosophia.taskManagement.dto.JobDTO;
import com.gosophia.taskManagement.dto.MissionDTO;
import com.gosophia.taskManagement.entity.Job;
import com.gosophia.taskManagement.service.TaskManagementService;
import com.gosophia.taskManagement.ws.TaskManagementWebService;
import com.gosophia.userManagement.dto.UserInfoDTO;
import com.gosophia.userManagement.entity.UserInfo;
import com.gosophia.userManagement.service.UserManagementService;

/**
 * 会议方案WebServiceImpl
 * 
 * @author nana
 * 
 */
@Service("ConferenceSchemeWebService")
@Transactional
public class ConferenceSchemeWebServiceImpl extends
		ConferenceHandleWebServiceImpl implements ConferenceSchemeWebService {

	@Autowired
	private TaskManagementService taskManagementService;
	@Autowired
	private TaskManagementWebService taskManagementWebService;

	@Autowired
	private UserManagementService userManagementService;

	@Autowired
	private ConferenceSchemeService conferenceSchemeService;
	
	private final Logger logger = Logger.getLogger(this.getClass());

	@Autowired
    private  Mapper dozer ;
	/**
	 * 新增方案业务数据
	 * 
	 * @param schemeJobData
	 *            不能为null,schemeJobData必须为null
	 * @throws BusinessException
	 */
	@Override
	public SchemeJobDataDTO addShemeJobData(SchemeJobDataDTO schemeJobDataDTO)
			throws BusinessException {
		Assert.notNull(schemeJobDataDTO, "schemeJobData不能为null");
		Assert.isNull(schemeJobDataDTO.getJobDataId(), "jobDataId必须为null");
		SchemeJobData schemeJobData = DozerChangeUtil.changeBeforeToAfter(
				schemeJobDataDTO, SchemeJobData.class);
		Job job = taskManagementService.findJobDetailByJobId(schemeJobDataDTO
				.getJobDTO().getJobId());
		schemeJobData.setJob(job);
		if (schemeJobDataDTO.getNextApproval() != null) {
			schemeJobData.setNextApproval(userManagementService
					.findUserInfoByUserInfoId(schemeJobDataDTO
							.getNextApproval().getUserInfoId()));
		}
		if (schemeJobDataDTO.getOnlineDocumentDTO() != null) {
			Document document = new Document();
			document.setDocumentPath(schemeJobDataDTO.getOnlineDocumentDTO()
					.getDocumentPath());
			document.setDocumentVersion(schemeJobDataDTO.getOnlineDocumentDTO()
					.getDocumentVersion());
			document.setDocumentCategory("online");
			schemeJobData.setOnlineDocument(document);
		}
		conferenceSchemeService.addConferenceJobData(schemeJobData);
		SchemeJobData schemeJobDataNew = (SchemeJobData) taskManagementService
				.findJobDataDetail(schemeJobDataDTO.getJobDTO().getJobId(),
						SchemeJobData.class);
		SchemeJobDataDTO schemeJobDataDTONew = DozerChangeUtil
				.changeBeforeToAfter(schemeJobDataNew, SchemeJobDataDTO.class);
		if (schemeJobDataNew.getOnlineDocument() != null) {
			DocumentDTO onlineDocument = DozerChangeUtil.changeBeforeToAfter(
					schemeJobDataNew.getOnlineDocument(), DocumentDTO.class);
			schemeJobDataDTONew.setOnlineDocumentDTO(onlineDocument);
		}
		return schemeJobDataDTONew;
	}

	@Override
	public List<JobDTO> findFinishedSchemeApprovalHistoryRecordByJobId(
			Long jobId) throws BusinessException {
		Assert.notNull(jobId, "jobId不能为null");
		Job job = taskManagementService.findJobDetailByJobId(jobId);
		Long missionId = job.getMission().getMissionId();
		List<Job> finishedHistoryList = taskManagementService
				.findJobByMissionTypeAndJobTypeFinished(missionId, "方案审批");
		List<JobDTO> historyDTOs = new ArrayList<JobDTO>();
		if (finishedHistoryList != null && finishedHistoryList.size() != 0) {
			for (Job j : finishedHistoryList) {
				JobDTO jDTO = DozerChangeUtil.changeBeforeToAfter(j,
						JobDTO.class);
				UserInfo user = j.getOperator();
				UserInfoDTO approval = DozerChangeUtil.changeBeforeToAfter(
						user, UserInfoDTO.class);
				jDTO.setOperatorDTO(approval);
				historyDTOs.add(jDTO);
			}
		}

		return historyDTOs;
	}

	@Override
	public SchemeJobDataDTO findPreConferenceJobDataDTOByJobId(Long jobId)
			throws BusinessException {
		Assert.notNull(jobId, "jobId不能为null");
		Job job = taskManagementService.findJobDetailByJobId(jobId);
		Job preJob = job.getPreviousJob();
		if (preJob == null) {
			return null;
		}
		Long preJobId = preJob.getJobId();
		SchemeJobData schemeJobData = (SchemeJobData) taskManagementService
				.findJobDataDetail(preJobId, SchemeJobData.class);
		if (schemeJobData == null) {
			return null;
		}
		SchemeJobDataDTO schemeJobDataDTO = DozerChangeUtil
				.changeBeforeToAfter(schemeJobData, SchemeJobDataDTO.class);
		if(schemeJobData.getOnlineDocument()!=null){
		    DocumentDTO docuemntDTO = DozerChangeUtil.changeBeforeToAfter(
	                schemeJobData.getOnlineDocument(), DocumentDTO.class);
	        schemeJobDataDTO.setOnlineDocumentDTO(docuemntDTO);
		}
		if(schemeJobData.getConferenceCreator()!=null){
		    schemeJobDataDTO.setConferenceCreatorDTO(dozer.map(schemeJobData.getConferenceCreator(), UserInfoDTO.class));
		}
		return schemeJobDataDTO;

	}

	@Override
	public SchemeJobDataDTO findSchemeJobDataDTOByJobId(Long jobId)
			throws BusinessException {
		Assert.notNull(jobId, "jobId不能为null");
		SchemeJobData schemeJobData = (SchemeJobData) taskManagementService
				.findJobDataDetail(jobId, SchemeJobData.class);
		if (schemeJobData == null) {
			return null;
		}
		SchemeJobDataDTO schemeJobDataDTO = DozerChangeUtil
				.changeBeforeToAfter(schemeJobData, SchemeJobDataDTO.class);
		if (schemeJobData.getOnlineDocument() != null) {
			DocumentDTO documentDTO = DozerChangeUtil.changeBeforeToAfter(
					schemeJobData.getOnlineDocument(), DocumentDTO.class);
			schemeJobDataDTO.setOnlineDocumentDTO(documentDTO);
		}
		if(schemeJobData.getConferenceCreator()!=null){
		    schemeJobDataDTO.setConferenceCreatorDTO(dozer.map(schemeJobDataDTO.getConferenceCreatorDTO(), UserInfoDTO.class));
		}
		if(schemeJobData.getImportantLevel()!=null){
		    schemeJobDataDTO.setImportantLevelDTO(dozer.map(schemeJobData.getImportantLevel(), DataValueDTO.class));
		}

		JobDTO jobDTO = DozerChangeUtil.changeBeforeToAfter(schemeJobData
				.getJob(), JobDTO.class);
		if (schemeJobData.getJob().getOperator() != null) {
			UserInfoDTO user = DozerChangeUtil.changeBeforeToAfter(
					schemeJobData.getJob().getOperator(), UserInfoDTO.class);
			jobDTO.setOperatorDTO(user);
		}

		schemeJobDataDTO.setJobDTO(jobDTO);
		return schemeJobDataDTO;
	}

	@Override
	public SchemeJobDataDTO updateSchemeJobData(SchemeJobDataDTO schemeJobDataDTO)
			throws BusinessException {
		Assert.notNull(schemeJobDataDTO, "schemeJobData不能为null");
		Assert.notNull(schemeJobDataDTO.getJobDTO().getJobId(), "jobId不能为null");
		
		SchemeJobData schemeJobData = DozerChangeUtil.changeBeforeToAfter(
				schemeJobDataDTO, SchemeJobData.class);
		if (schemeJobDataDTO.getOnlineDocumentDTO() != null) {
			Document document = DozerChangeUtil.changeBeforeToAfter(
					schemeJobDataDTO.getOnlineDocumentDTO(), Document.class);
			document.setDocumentCategory("online");
			schemeJobData.setOnlineDocument(document);
		}

		Job job = taskManagementService.findJobDetailByJobId(schemeJobDataDTO
				.getJobDTO().getJobId());
		
		schemeJobData.setJob(job);
		if (schemeJobDataDTO.getNextApproval() != null) {
			schemeJobData.setNextApproval(userManagementService
					.findUserInfoByUserInfoId(schemeJobDataDTO
							.getNextApproval().getUserInfoId()));
		}
		SchemeJobData schemeJobDataOld = (SchemeJobData) taskManagementService
		.findJobDataDetail(schemeJobDataDTO.getJobDTO().getJobId(),
				SchemeJobData.class);
		schemeJobData.setVersion(schemeJobDataOld.getVersion());
		schemeJobData.setOpinion(schemeJobDataDTO.getOpinion());
		conferenceSchemeService.updateConferenceJobData(schemeJobData);
		SchemeJobData schemeJobDataNew = (SchemeJobData) taskManagementService
				.findJobDataDetail(schemeJobDataDTO.getJobDTO().getJobId(),
						SchemeJobData.class);
		SchemeJobDataDTO schemeJobDataDTONew = DozerChangeUtil
				.changeBeforeToAfter(schemeJobDataNew, SchemeJobDataDTO.class);
		if (schemeJobDataNew.getOnlineDocument() != null) {
			DocumentDTO onlineDocument = DozerChangeUtil.changeBeforeToAfter(
					schemeJobDataNew.getOnlineDocument(), DocumentDTO.class);
			schemeJobDataDTONew.setOnlineDocumentDTO(onlineDocument);
		}
		return schemeJobDataDTONew;
	}

	@Override
	public void HandleConferenceSchemeTurning(Long jobId, Long operatorId,
			SchemeJobDataDTO schemeJobDataDTO) throws BusinessException {
		Assert.notNull(jobId, "jobId不能为null");
		Assert.notNull(operatorId, "进行流转时操作人Id不能为空");
		Assert.notNull(schemeJobDataDTO, "schemeJobData不能为null");
		SchemeJobData schemeJobData;
		Document document;
		if (schemeJobDataDTO.getJobDataId() != null) {
			schemeJobData = (SchemeJobData) taskManagementService
					.findJobDataDetail(jobId, SchemeJobData.class);
			document = schemeJobData.getOnlineDocument();
		} else {
			schemeJobData = new SchemeJobData();
			document = new Document();
		}

		document.setDocumentPath(schemeJobDataDTO.getOnlineDocumentDTO()
				.getDocumentPath());
		document.setDocumentVersion(schemeJobDataDTO.getOnlineDocumentDTO()
				.getDocumentVersion());
		schemeJobData.setOnlineDocument(document);
		if (schemeJobDataDTO.getNextApproval() != null
				&& schemeJobDataDTO.getNextApproval().getUserInfoId() != null) {
			schemeJobData.setNextApproval(userManagementService
					.findUserInfoByUserInfoId(schemeJobDataDTO
							.getNextApproval().getUserInfoId()));
		}
		schemeJobData.setOpinion(schemeJobDataDTO.getOpinion());
		schemeJobData.setTurningAction(schemeJobDataDTO.getTurningAction());
		conferenceSchemeService.HandleConferenceTurning(jobId, operatorId,
				schemeJobData);
	}
//2011-6-2新增方法
    @Override
    public void deleteSchemeTransientStore(Long schemeTransientStoreId)
            throws BusinessException {
        Assert.notNull(schemeTransientStoreId,"schemeTransientStoreId不能为null");
        conferenceSchemeService.deleteSchemeTransientStore(schemeTransientStoreId);
    }


    @Override
    public Page<SchemeTransientStoreDTO> findSchemeTransientStoreByPage(
            Long userInfoId, int pageSize,int pageNo,
            List<PropertyFilter> propertyFilters,
            List<OrderCondition> orderConditions) throws BusinessException,
            ParameterException, ConcurrencyException, TechnicalException {
        Page<SchemeTransientStore> page = new Page<SchemeTransientStore>();
        page.setPageNo(pageNo);
        page.setPageSize(pageSize);
        
        page = conferenceSchemeService.findSchemeTransientStoreByPage(userInfoId, page, propertyFilters, orderConditions);
        
        List<SchemeTransientStoreDTO> listReturn = entityToDTO(page.getResult());
        
        Page<SchemeTransientStoreDTO> pageReturn = new Page<SchemeTransientStoreDTO>();
        pageReturn.setPageNo(pageNo);
        pageReturn.setPageSize(pageSize);
        pageReturn.setResult(listReturn);
        pageReturn.setTotalCount(page.getTotalCount());
        
        return pageReturn;
    }
    
    @Override
	public Page<SchemeTransientStoreDTO> findTransientStoreBySearchNameAndPage(
			Long userInfoId, int pageSize, String searchStr, int pageNo,
			List<PropertyFilter> propertyFilters,
			List<OrderCondition> orderConditions) throws BusinessException,
			ParameterException, ConcurrencyException, TechnicalException {
		Page<SchemeTransientStore> page = new Page<SchemeTransientStore>();
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		
		page = conferenceSchemeService.findSchemeTransientStoreSimplePage(userInfoId, page, searchStr, propertyFilters, orderConditions);
		
		List<SchemeTransientStoreDTO> listReturn = entityToDTO(page.getResult());
		
		Page<SchemeTransientStoreDTO> pageReturn = new Page<SchemeTransientStoreDTO>();
		pageReturn.setPageNo(pageNo);
		pageReturn.setPageSize(pageSize);
		pageReturn.setResult(listReturn);
		pageReturn.setTotalCount(page.getTotalCount());
		
		return pageReturn;
	}
    
    @Override
    public SchemeTransientStoreDTO findTransientStoreByJobId(Long jobId)
            throws BusinessException {
        Assert.notNull(jobId,"jobId不能为null");
        SchemeTransientStore  s = conferenceSchemeService.findTransientStoreByJobId(jobId);
        if(s!=null){
            SchemeTransientStoreDTO schemeTransientStoreDTO = dozer.map(s, SchemeTransientStoreDTO.class);
            
            if(s.getCommandPerson()!=null){
                schemeTransientStoreDTO.setCommandPersonDTO(dozer.map(s.getCommandPerson(),UserInfoDTO.class));
            }
            if(s.getCreator()!=null){
                schemeTransientStoreDTO.setCreatorDTO(dozer.map(s.getCreator(),UserInfoDTO.class));
            }
            if(s.getImportance()!=null){
                schemeTransientStoreDTO.setImportanceDTO(dozer.map(s.getImportance(), DataValueDTO.class));
            }
            if(s.getSchemeDocument()!=null){
                schemeTransientStoreDTO.setSchemeDocumentDTO(dozer.map(s.getSchemeDocument(), DocumentDTO.class));
            }
            return schemeTransientStoreDTO;
        }else{
            return null;
        }
    }

    private List<SchemeTransientStoreDTO> entityToDTO(List<SchemeTransientStore> entities){
       
        List<SchemeTransientStoreDTO> dtos = new ArrayList<SchemeTransientStoreDTO>();
        
        if(entities!=null && entities.size()!=0){
            
            for(SchemeTransientStore s:entities){
                SchemeTransientStoreDTO schemeTransientStoreDTO = dozer.map(s, SchemeTransientStoreDTO.class);
                if(s.getCommandPerson()!=null){
                    schemeTransientStoreDTO.setCommandPersonDTO(dozer.map(s.getCommandPerson(),UserInfoDTO.class));
                }
                if(s.getCreator()!=null){
                    schemeTransientStoreDTO.setCreatorDTO(dozer.map(s.getCreator(),UserInfoDTO.class));
                }
                if(s.getImportance()!=null){
                    schemeTransientStoreDTO.setImportanceDTO(dozer.map(s.getImportance(), DataValueDTO.class));
                }
                if(s.getSchemeDocument()!=null){
                    schemeTransientStoreDTO.setSchemeDocumentDTO(dozer.map(s.getSchemeDocument(), DocumentDTO.class));
                }
                dtos.add(schemeTransientStoreDTO);
            }
        }
        return dtos;
    }
    @Override
    public Long saveOrUpdateSchemeTransientStore(
            SchemeTransientStoreDTO schemeTransientStoreDTO)
            throws BusinessException {
        Assert.notNull(schemeTransientStoreDTO,"schemeTransientStoreDTO不能为null");
        SchemeTransientStore schemeTransientStore = dozer.map(schemeTransientStoreDTO, SchemeTransientStore.class);
        if(schemeTransientStoreDTO.getCommandPersonDTO()!=null){
            schemeTransientStore.setCommandPerson(dozer.map(schemeTransientStoreDTO.getCommandPersonDTO(),UserInfo.class));
        }
        if(schemeTransientStoreDTO.getCreatorDTO()!=null){
            schemeTransientStore.setCreator(dozer.map(schemeTransientStoreDTO.getCreatorDTO(),UserInfo.class));
        }
        if(schemeTransientStoreDTO.getImportanceDTO()!=null){
            schemeTransientStore.setImportance(dozer.map(schemeTransientStoreDTO.getImportanceDTO(), DataValue.class));
        }
        if(schemeTransientStoreDTO.getSchemeDocumentDTO()!=null){
            schemeTransientStore.setSchemeDocument(dozer.map(schemeTransientStoreDTO.getSchemeDocumentDTO(), Document.class));
        }
        Long id=conferenceSchemeService.saveOrUpdateSchemeTransientStore(schemeTransientStore);
        return id;
        
    }

	@Override
	public SchemeTransientStoreDTO findTransientStoreById(Long id)
			throws BusinessException {
		 Assert.notNull(id,"id不能为null");
		 SchemeTransientStore  s = conferenceSchemeService.findTransientStoreById(id);
	        
	        SchemeTransientStoreDTO schemeTransientStoreDTO = dozer.map(s, SchemeTransientStoreDTO.class);
	        
	        if(s.getCommandPerson()!=null){
	            schemeTransientStoreDTO.setCommandPersonDTO(dozer.map(s.getCommandPerson(),UserInfoDTO.class));
	        }
	        if(s.getCreator()!=null){
	            schemeTransientStoreDTO.setCreatorDTO(dozer.map(s.getCreator(),UserInfoDTO.class));
	        }
	        if(s.getImportance()!=null){
	            schemeTransientStoreDTO.setImportanceDTO(dozer.map(s.getImportance(), DataValueDTO.class));
	        }
	        if(s.getSchemeDocument()!=null){
	            schemeTransientStoreDTO.setSchemeDocumentDTO(dozer.map(s.getSchemeDocument(), DocumentDTO.class));
	        }
	        return schemeTransientStoreDTO;
	}

    @Override
    public MissionDTO findMissionByJobId(Long jobId) throws BusinessException {
        Assert.notNull(jobId,"jobId不能为null");
        JobDTO jobDTO = taskManagementWebService.findJobDetailByJobId(jobId);
        if(jobDTO==null){
            return null;
        }else{
            return jobDTO.getMissionDTO();
        }
    }
	

}
